package com.servlet;

import com.daofactory.DaoFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author 徐洲
 * @version 1.0
 */
public class ArticleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIRECTORY = "/upload/";
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        if ("add".equals(action) || "edit".equals(action)) {
            if (!ServletFileUpload.isMultipartContent(request)) {
                // 如果不是则停止
                session.setAttribute("info", "Error: 表单必须包含 enctype=multipart/form-data");
                response.sendRedirect("./infoPage.jsp");
                return;
            }
            String article_id = "";
            String userid = "";
            String article_title = "";
            String category_id = "";
            String article_cover = "";
            String content = "";
            try {
                //设置ContentType字段值
                response.setContentType("text/html;charset=utf-8");
                // 创建DiskFileItemFactory工厂对象
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
                factory.setSizeThreshold(MEMORY_THRESHOLD);
                //设置文件缓存目录，如果该目录不存在则新创建一个
                File f = new File("D:\\Learn\\javaweb\\tempImg");
                if (!f.exists()) {
                    f.mkdirs();
                }
                // 设置文件的缓存路径
                factory.setRepository(f);
                // 创建 ServletFileUpload对象
                ServletFileUpload fileupload = new ServletFileUpload(factory);
                //设置字符编码
                fileupload.setHeaderEncoding("utf-8");
                //设置字符编码,中文处理
                fileupload.setHeaderEncoding("utf-8");
                // 设置最大文件上传值
                fileupload.setFileSizeMax(MAX_FILE_SIZE);
                // 设置最大请求值 (包含文件和表单数据)
                fileupload.setSizeMax(MAX_REQUEST_SIZE);
                // 解析 request，得到上传文件的FileItem对象
                ServletRequestContext src = new ServletRequestContext(request);
                List<FileItem> fileitems = fileupload.parseRequest(src);

                // 遍历集合
                for (FileItem fileitem : fileitems) {
//                    String userid = request.getParameter("userid");
//                    String article_title = request.getParameter("article_title");
//                    String category_id = request.getParameter("category_id");
//                    String article_cover = request.getParameter("article_cover");
//                    String content = request.getParameter("content");
                    // 判断是否为普通字段
                    if (fileitem.isFormField()) {
                        // 获得字段名和字段值
                        String name = fileitem.getFieldName();
                        if(name.equals("userid")){
                            //如果文件不为空，将其保存在value中
                            if(!fileitem.getString().equals("")){
                                userid = fileitem.getString("utf-8");
                            }
                        }
                        if(name.equals("article_title")){
                            //如果文件不为空，将其保存在value中
                            if(!fileitem.getString().equals("")){
                                article_title = fileitem.getString("utf-8");
                            }
                        }
                        if(name.equals("category_id")){
                            //如果文件不为空，将其保存在value中
                            if(!fileitem.getString().equals("")){
                                category_id = fileitem.getString("utf-8");
                            }
                        }
                        if(name.equals("content")){
                            //如果文件不为空，将其保存在value中
                            if(!fileitem.getString().equals("")){
                                content = fileitem.getString("utf-8");
                            }
                        }
                        if (name.equals("article_id")){
                            //如果文件不为空，将其保存在value中
                            if(!fileitem.getString().equals("")){
                                article_id = fileitem.getString("utf-8");
                            }
                        }
                    } else {
                        // 获取上传的文件名
                        String filename = fileitem.getName();
                        //处理上传文件
                        if(filename != null && !filename.equals("")){
                            // 截取出上传文件名
                            filename = filename.substring(filename.lastIndexOf("\\") + 1);
                            // 文件名需要唯一
                            filename = UUID.randomUUID().toString() + "_" + filename;
                            // 在服务器创建同名文件
                            String webPath = UPLOAD_DIRECTORY;
                            //将服务器中文件夹路径与文件名组合成完整的服务器端路径
                            String filepath = getServletContext().getRealPath(webPath) + File.separator + filename;
                            // 创建文件
                            File file = new File("D:\\Learn\\javaweb\\web" + webPath + "\\article\\" + filename);
                            file.getParentFile().mkdirs();
                            file.createNewFile();
                            // 获得上传文件流
                            InputStream in = fileitem.getInputStream();
                            // 使用FileOutputStream打开服务器端的上传文件
                            FileOutputStream out = new FileOutputStream(file);
                            // 流的对拷
                            byte[] buffer = new byte[1024];//每次读取1个字节
                            int len;
                            //开始读取上传文件的字节，并将其输出到服务端的上传文件输出流中
                            while ((len = in.read(buffer)) > 0)
                                out.write(buffer, 0, len);

                            article_cover = filename;
                            // 关闭流
                            in.close();
                            out.close();
                            // 删除临时文件
                            fileitem.delete();
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            if ("add".equals(action)){
                if (DaoFactory.getArticleDAOInstance().addArticle(article_title, userid, category_id, article_cover, content)){
                    session.setAttribute("info", "发布文章成功");
                }else {
                    session.setAttribute("info", "发布文章失败");
                }
            } else if ("edit".equals(action)) {
                if (DaoFactory.getArticleDAOInstance().editArticle(article_id, article_title, userid, category_id, article_cover, content)){
                    session.setAttribute("info", "修改文章成功");
                }else {
                    session.setAttribute("info", "修改文章失败");
                }
            }
        } else if ("collect".equals(action)){
            String userid = request.getParameter("userid");
            String article_id = request.getParameter("article_id");
            if (DaoFactory.getArticleDAOInstance().collectArticle(userid, article_id)){
                session.setAttribute("info", "收藏成功");
            }else {
                session.setAttribute("info", "收藏失败");
            }
        }else if ("noCollect".equals(action)){
            String userid = request.getParameter("userid");
            String article_id = request.getParameter("article_id");
            if (DaoFactory.getArticleDAOInstance().noCollectArticle(userid, article_id)){
                session.setAttribute("info", "取消收藏成功");
            }else {
                session.setAttribute("info", "取消收藏失败");
            }
        } else if ("deleteAll".equals(action)){
            String[] ids = request.getParameterValues("checkAll");
            if (DaoFactory.getArticleDAOInstance().deleteAllArticle(ids)){
                session.setAttribute("info", "删除文章成功");
            }else {
                session.setAttribute("info", "删除文章失败");
            }
        }

        response.sendRedirect("./infoPage.jsp");
    }
}
